package business

import (
	"errors"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
)

var DocB = new(docBus)

type docBus struct {
}

func (*docBus) GetList(req *filter.DocReq) (any, int64, error) {
	docList, cnt, err := model.DocM.GetList(req)
	list := make([]*filter.DocNodeRes, 0)
	for _, v := range docList {
		list = append(list, &filter.DocNodeRes{
			Id:       v.Id,
			Title:    v.Title,
			Type:     v.Type,
			Pid:      v.Pid,
			BookId:   v.BookId,
			Link:     v.Link,
			Sort:     v.Sort,
			Status:   v.Status,
			Children: nil,
		})

	}
	list = DocB.GetTreeRecursive(list, 0)
	return list, cnt, err
}

// 递归回去函数  TODO:需要优化
func (*docBus) GetTreeRecursive(list []*filter.DocNodeRes, parentId int) []*filter.DocNodeRes {
	res := make([]*filter.DocNodeRes, 0)
	for _, v := range list {
		if v.Pid == parentId {
			v.Children = DocB.GetTreeRecursive(list, conv.Int(v.Id))
			res = append(res, v)
		}
	}
	return res
}

func (*docBus) Add(req *filter.DocAddReq) (uint, error) {
	if conv.IsEmpty(req.Title) {
		return 0, errors.New("目录名不能为空！")
	}
	req.AddTime = conv.NowUnix()
	req.UpdateTime = conv.NowUnix()
	res, err := model.DocM.Add(req)
	if err != nil {
		return 0, err
	}
	return res, nil
}

func (*docBus) GetUpdateInfo(req *filter.DocGetUpdateInfoReq) (any, error) {
	info, err := model.DocM.GetDocById(conv.Int(req.Id))
	if err != nil {
		return nil, err
	}
	return info, nil
}

func (*docBus) Update(req *filter.DocUpdateReq) (uint, error) {
	req.UpdateTime = conv.NowUnix()
	res, err := model.DocM.Update(req)
	if err != nil {
		return 0, err
	}
	return res, nil
}

func (*docBus) UpdateExt(req map[string]interface{}) error {
	err := model.DocM.UpdateExt(req)
	if err != nil {
		return err
	}
	return nil
}

func (*docBus) Delete(req *filter.BookDeleteReq) (uint, error) {
	ids := conv.Slice(req.Id)
	res, err := model.BookM.Delete(ids)
	if err != nil {
		return 0, err
	}
	return res, nil
}
